import axios from 'axios'

export default {
  namespaced: true,
  state: {
    list: []
  },
  mutations: {
    updateList (state, val) {
      state.list = val
    },
    // 修改状态
    updateState (state, id) {
      const row = state.list.find(item => item.id === id)
      row.goods_state = !row.goods_state
    },
    // 修改数量
    updateCount (state, obj) {
      const row = state.list.find(item => item.id === obj.id)
      if (obj.val === -1 && row.goods_count === 1) return
      row.goods_count += obj.val
    },
    // 修改全部商品的状态(boo是组件传递过来的 true或false)
    updateAllState (state, boo) {
      state.list.forEach(item => {
        item.goods_state = boo
      })
    }
  },
  actions: {
    async initData (store) {
      const { data } = await axios.get('http://www.itcbc.com:3006/api/cart')
      store.commit('updateList', data.list)
    }
  },
  getters: {
    // 计算已选商品的总数量
    count (state) {
      const yixuanze = state.list.filter(item => item.goods_state === true)
      return yixuanze.reduce((t, c) => t + c.goods_count, 0)
    },
    // 计算已选商品的总价格
    total (state) {
      const yixuanze = state.list.filter(item => item.goods_state === true)
      return yixuanze.reduce((t, c) => t + c.goods_count * c.goods_price, 0)
    },
    // 控制全选是否选中
    isFull (state) {
      return state.list.every(item => item.goods_state === true)
    }
  }
}
